<template>
  <div class="content">
    <div v-for="item in arr">
      <!-- <img class="lazy" width="360" height="auto" :data-src="item" src="/src/assets/vue.svg" alt=""> -->
      <img width="360" height="auto" v-lazy="item" alt="">
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, Directive, DirectiveBinding} from "vue"
// glob       懒加载模式
// let modules = {
//   'xxxx': () => import('')
// }

// globEager  静态加载模式
// import xxxx from "xxxx"

// let imageList = import.meta.globEager("./assets/images/*.*") // globEager 已被弃用
let imageList:Record<string, {default: string}> = import.meta.glob("./assets/images/*.*", {eager: true}) // 获取图片列表
let arr = Object.values(imageList).map(item => item.default)
console.log(imageList, arr)

// 传统实现懒加载
/* document.addEventListener("DOMContentLoaded", function() {
  let lazyImgs = [].slice.call(document.querySelectorAll('.lazy'));
  let body = document.body;
  let active = false;

  let lazyLoad = function() {
    if(active === false) {
      active = true;
      setTimeout(function() {
        lazyImgs.forEach(function(lazyImg) {
          if(
            (lazyImg.getBoundingClientRect().top <= window.innerHeight && lazyImg.getBoundingClientRect().bottom >= 0) && 
            getComputedStyle(lazyImg).display !== "none"
          ) {
            lazyImg.src = lazyImg.dataset.src;
            lazyImg.removeAttribute("data-src");
            lazyImg.classList.remove("lazy");

            lazyImgs = lazyImgs.filter(img => img !== lazyImg)

            if(lazyImgs.length === 0) {
              body.removeEventListener("scroll", lazyLoad)
              window.removeEventListener("resize", lazyLoad)
              window.removeEventListener("orientationchange", lazyLoad)
            }
          }
        })
        
        active = false
      }, 200)
    }
  }

  body.addEventListener("scroll", lazyLoad)
  window.addEventListener("resize", lazyLoad)
  window.addEventListener("orientationchange", lazyLoad)
}) */

// 现代实现懒加载
let vLazy:Directive<HTMLImageElement, string> = async (el, bingding) => {
  const def = await import("./assets/vue.svg")
  el.src = def.default

  const observer = new IntersectionObserver((entries) => {
    console.log(entries)
    if(entries[0].intersectionRatio > 0) {
      el.src = bingding.value
      observer.unobserve(el)
    }
  })

  observer.observe(el)
}

</script>

<style lang="less">
body {
  overflow: auto !important;
}
</style>